import 'package:flutter/material.dart';

import '../../resources/kq_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../button/kq_ink_well.dart';
import '../divider/kq_divider.dart';

/// 通用列表对话框
///
/// @author 周卓
///
class KqListDialog<T> extends AlertDialog {
  final double? width;

  /// 数据源
  final List<T> items;

  /// 转换 T -> String 转换
  final String Function(int index, T item)? nameConvert;

  /// 回调
  final Function(int index, T item)? callback;

  const KqListDialog(
      {Key? key,
      required this.items,
      this.width,
      this.nameConvert,
      this.callback})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final List<Widget> children = <Widget>[];

    // 小诸葛规范，最多显示6个，多余滚动
    var maxHeight = 6 * 50.0;

    /// item
    for (int i = 0; i < items.length; i++) {
      var item = items[i];
      String title;
      if (nameConvert != null) {
        title = nameConvert!(i, item);
      } else {
        if (item is String) {
          title = item;
        } else if (item is Map) {
          title = item['title'];
        } else {
          title = '';
        }
      }
      children.add(KqInkWell(
        onTap: () => {
          if (callback != null) {callback!(i, item)}
        },
        child: Container(
          height: 50,
          alignment: Alignment.center,
          width: double.infinity,
          padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 20),
          child: Text(
            title,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                fontSize: 16,
                color: KqThemeManager.instance
                        .getConfig()
                        .dialogConfig
                        .itemTextColor ??
                    KqThemeColors.text26),
          ),
        ),
      ));
      if (i < (items.length - 1)) {
        children.add(const KqDivider());
      }
    }

    Widget dialogChild = Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: children,
    );
    return UnconstrainedBox(
        child: SizedBox(
            width: width ?? 320,
            child: Material(
                shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(8))),
                color:
                    KqThemeManager.instance.getConfig().dialogConfig.bgColor ??
                        KqThemeColors.bgWhite,
                child: LimitedBox(
                  maxHeight: maxHeight,
                  child: ClipRRect(
                    borderRadius: const BorderRadius.all(Radius.circular(8)),
                    child: SingleChildScrollView(
                      child: dialogChild,
                    ),
                  ),
                ))));
  }
}
